<?php

namespace app\api\controller;

use app\admin\model\express\Companys;
use app\admin\model\kd\Callback;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\product\Sku;
use app\admin\model\product\Value;
use app\admin\model\Transport;
use app\common\controller\Kd100;
use think\Db;
use think\Exception;
use think\Request;
use app\common\controller\Api;

class Productlisto extends Api
{
    protected static $model = null;
    protected $noNeedLogin = ['logisticsInfo', 'logisticsCallBack'];
    protected $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Listo();
    }

    /**
     * 商品结算
     */
    public function preOrder()
    {
        $data = input('data');

        if (!$data) {
            $this->error('参数缺失！');
        }

        $dataArr = [];
        $data1 = explode('|', $data);
        foreach ($data1 as $v1) {
            $arr1 = explode(',', $v1);
            $item = [];
            foreach ($arr1 as $v2) {
                $arr2 = explode(':', $v2);
                if ($arr2[0] == 'sku_id') {
                    $item['sku_id'] = $arr2[1];
                } elseif ($arr2[0] == 'number') {
                    $item['number'] = $arr2[1];
                }
            }

            $dataArr[] = $item;
        }

        if (count($dataArr) <= 0) {
            $this->error('请至少选择一个商品！');
        }

        $id = $this->auth->id;
        $tag = create_order($id);
        $list = [];
        $number = 0;
        $total = 0.00;

        foreach ($dataArr as $v) {
            if ($v['sku_id'] <= 0) {
                $this->error('商品规格缺失！');
            }
            $skuInfo = Sku::find($v['sku_id']);
            if ($skuInfo->stock < $v['number']) {
                $this->error('商品余量不足！');
            }
            $productInfo = Lists::where('id', $skuInfo->product_id)->find();

            $attrs_arr = json_decode($skuInfo->attrs, true);
            $vals = [];
            foreach ($attrs_arr as $v1) {
                $arr = explode(':', $v1);
                $value_name = Value::where('id', $arr[1])->value('name');
                array_push($vals, $value_name);
            }

            $parameters = implode('/', $vals);
            $time = time();
            $item = [
                'product_id' => $skuInfo->product_id,
                'product_name' => $productInfo->name,
                'num' => $v['number'],
                'user_id' => $id,
                'tag' => $tag,
                'sku_id' => $v['sku_id'],
                'parameters' => $parameters,
                'price' => $skuInfo->price,
                'total' => round($skuInfo->price * $v['number'], 2),
                'createtime' => $time,
                'updatetime' => $time
            ];

            array_push($list, $item);

            $number += $v['number'];
            $total += round($skuInfo->price * $v['number'], 2);
        }

        $res = self::$model->insertAll($list);
        if ($res) {
            $this->success('生成商品清单！', $tag);
        } else {
            $this->error('操作失败！');
        }
    }

    /**
     * 获取商品清单
     */
    public function getOrder()
    {
        $user_id = $this->auth->id;
        $tag = input('tag');
        $lists = self::$model->field('id,product_id,product_name,num,price,parameters,total')->where("tag", $tag)->where('user_id', $user_id)->order('id desc')->select();

        $total = $num = $transfee = 0;
        foreach ($lists as &$val) {
            $pInfo = Lists::where('id', $val['product_id'])->find();
//            $val['goodname'] = $pInfo['goodname'];
            $val['cover_ico'] = make_full_url($pInfo['image']);
            $val['intro'] = $pInfo['intro'];

            $total += $val['total'];
            $num += $val['num'];        //商品数量
            $transfee += $pInfo['transfee'] * $val['num'];
        }

        $data = [
            'list' => $lists,
            'transfee' => $transfee,
            'num' => $num,
            'total' => $total,
        ];

        $this->success('商品清单！', $data);
    }

    /**
     * 订单物流信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function logisticsInfo()
    {
        $id = input('id');
        $orderInfo = self::$model->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('该订单不存在！');
        }

        if ($orderInfo->status < 10) {
            $this->error('该订单未发货！');
        }
        if (!$orderInfo->toolid || !$orderInfo->tool) {
            $this->error('快递信息缺失！');
        }

        $code = Companys::where('id', $orderInfo->toolid)->value('code');
        $addressId = \app\admin\model\product\Order::where('id', $orderInfo->order_id)->value('addressid');
        $mobile = Transport::where('id', $addressId)->value('mobile');
        $data = (new Kd100())->logisticsInfo($code, $orderInfo->tool, $mobile);
        if ($data['code'] == 0) {
            $this->error($data['msg']);
        }

        $this->success('物流轨迹为', $data['data']);
    }

    /**
     * 快递消息回调
     */
    public function logisticsCallBack()
    {
        $data = $_POST['param'];
        if (!$data) {
            echo json_encode([
                "result" => false,
                "returnCode" => "500",
                "message" => "数据非法"
            ]);
            die;
        }
        // 存储数据
        Callback::create([
            'content' => $data
        ]);
        $data = json_decode($data, true);
        $res = $data['lastResult'];
        $state = $res['state'];
        $info = reset($res["data"]);
        if (!$info) {
            echo json_encode([
                "result" => false,
                "returnCode" => "500",
                "message" => "数据非法"
            ]);
            die;
        }

        $tool = $res['nu'];
        $linfo = self::$model->where('tool', $tool)->find();
        if (in_array($linfo->backinfo, ['fail', 'success'])) {
            echo json_encode([
                "result" => true,
                "returnCode" => "200",
                "message" => "成功"
            ]);
            die;
        }

        $time = strtotime($info['time']);
//        $res = Listo::find(26)->toArray();
//        $state = $res['status'];

        $state_arr = [
            1 => 10,//发货
            0 => 11,//在途
            5 => 12,//派件
            6 => 13,//退回
            4 => 14,//退签
            7 => 15,//转投
            2 => 16,//疑难
            14 => 17,//拒签
            3 => 20,//签收
        ];

        $status = $state_arr[$state];
        if ($status == 20) {
            // 签收
            $ldata = [
                'status' => $status,
                'backinfo' => 'success',
                'finish_time' => $time,
                'updatetime' => $time
            ];
        } else {
            $ldata = [
                'status' => $status,
            ];

            if ($status == 13) {
                $ldata['backinfo'] = 'fail';
                $ldata['updatetime'] = $time;
            }
        }

        Db::startTrans();
        try {

//                $tool = $res['tool'];
            $lists = self::$model->where('tool', $tool)->select();

            foreach ($lists as $val) {
                Db::name('product_listo')->where('id', $val->id)->update($ldata);
                $num = self::$model->where('order_id', $val->order_id)->where('status', 'lt', $status)->count();
                if ($num == 0) {
                    Db::name('product_order')->where('id', $val->order_id)->update($ldata);
                }

                $oInfo = \app\admin\model\product\Order::where('id', $val->order_id)->find();
            }

            $department_user_id = $oInfo->department_user_id;
            if (in_array($status, [13, 20])) {
                if ($status == 20) {
                    $type = 'profile';
                    $money = round($oInfo->total * $oInfo->rate * 0.01, 2);
                    $content = '您好，运单号' . $tool . '的商品已被签收，分红到账' . $money . '元';
                    (new Common())->sendAppMsg($department_user_id, 'notice', '盈利消息', $content);
                } else {
                    $type = 'cost';
                    $content = '您好，运单号' . $tool . '的商品已被退回，产生物流损耗' . $oInfo->transfee . '元';
                    (new Common())->sendAppMsg($department_user_id, 'notice', '损耗消息', $content);
                }

                $ndata = [
                    'user_id' => $department_user_id,
                    'type' => $type,
                    'relation_id' => $oInfo->id,
                    'content' => $content,
                    'is_read' => 0,
                ];
                \app\admin\model\Notices::create($ndata);

                $user = \app\admin\model\department\User::find($department_user_id);
                if ($user->is_leader == 0) {
                    $luser = \app\admin\model\department\User::where('department_id', $user->department_id)
                        ->where('is_leader', 1)
                        ->find();
                    if ($luser) {

                        $content = str_replace('您好，', '您好，' . $user->username . '的', $content);
                        $ndata = [
                            'user_id' => $luser->id,
                            'type' => $type,
                            'relation_id' => $oInfo->id,
                            'content' => $content,
                            'is_read' => 0,
                        ];
                        \app\admin\model\Notices::create($ndata);
                    }
                }
            }

            if (in_array($status, [15, 16, 17])) {
                (new Common())->sendAppMsg($department_user_id, 'badge');
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
        }

        echo json_encode([
            "result" => true,
            "returnCode" => "200",
            "message" => "成功"
        ]);
        die;
    }
}